package com.example.ecommerce.service.impl;

import com.example.ecommerce.service.UserService;
import com.example.ecommerce.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import java.time.LocalDateTime;
import javax.servlet.http.HttpServletRequest;
import com.example.ecommerce.service.AuthService;
import com.example.ecommerce.dto.LoginRequestDTO;
import com.example.ecommerce.dto.LoginResponseDTO;
import com.example.ecommerce.entity.User;
import com.example.ecommerce.mapper.UserMapper;

import com.example.ecommerce.exception.BusinessException;

@Service
@Transactional(rollbackFor = Exception.class)
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

//    @Autowired
//    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    @Value("${jwt.refresh-token-expiration}")
    private Long refreshTokenExpiration;

    @Override
    public LoginResponseDTO login(LoginRequestDTO loginRequest) {
        // 查询用户
        User user = userService.login(loginRequest);
        if (user == null) {
            throw new BusinessException("用户名或密码错误");
        }
        
        // 验证密码
        if (!loginRequest.getPassword().equals(user.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }
        
        // 验证用户状态
        if (user.getStatus() != 1) {
            throw new BusinessException("账号已被禁用");
        }
        
        // 生成token
        String accessToken = jwtUtils.generateToken(user.getId());
        String refreshToken = jwtUtils.generateRefreshToken(user.getId());
        
        // 更新最后登录信息
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setLastLoginTime(LocalDateTime.now());
        updateUser.setLastLoginIp(getClientIp());
        userMapper.updateById(updateUser);
        
        // 构建返回数据
        LoginResponseDTO response = new LoginResponseDTO();
        response.setAccessToken(accessToken);
        response.setRefreshToken(refreshToken);
        response.setTokenType("Bearer");
        response.setExpiresIn(jwtUtils.getExpiration());
        
        return response;
    }

    @Override
    public String refreshToken(String refreshToken) {
        // 验证refresh token
        if (!jwtUtils.validateRefreshToken(refreshToken)) {
            throw new BusinessException("无效的refresh token");
        }
        
        // 获取用户ID
        Long userId = jwtUtils.getUserIdFromRefreshToken(refreshToken);
        
        // 验证用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 验证用户状态
        if (user.getStatus() != 1) {
            throw new BusinessException("账号已被禁用");
        }
        
        // 生成新的access token
        return jwtUtils.generateToken(userId);
    }

    @Override
    public void logout() {
        // 获取当前用户ID
        Long userId = jwtUtils.getUserIdFromRequest();
        if (userId == null) {
            return;
        }
        
        // 这里可以添加token黑名单等逻辑
        // 如果使用Redis，可以将token加入黑名单
    }

    /**
     * 获取客户端IP
     */
    private String getClientIp() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
                
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.hasText(ip)) {
            return ip.split(",")[0].trim();
        }
        
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.hasText(ip)) {
            return ip;
        }
        
        return request.getRemoteAddr();
    }
} 